import path from 'node:path';

import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { defineConfig } from 'vite';
import qiankun from 'vite-plugin-qiankun';

export default defineConfig({
  // 环境变量配置
  define: {
    'import.meta.env.VITE_APP_BASE_API': JSON.stringify('/dev-api'),
    'import.meta.env.VITE_APP_BASE_URL': JSON.stringify('http://localhost:8080'),
    'import.meta.env.VITE_APP_TITLE': JSON.stringify('系统管理-开发环境'),
    'import.meta.env.VITE_APP_ENV': JSON.stringify('development'),
    'import.meta.env.VITE_APP_DEBUG': JSON.stringify(true),
  },

  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },

  server: {
    port: 3005,
    host: '0.0.0.0',
    cors: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control',
    },
    fs: {
      allow: ['..', '../..', '../../..'],
    },
    // API 代理配置
    proxy: {
      '/dev-api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        // 不重写路径，保留 /dev-api 前缀发送给后端
        rewrite: (path) => path,
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('[SystemApp Proxy] 请求:', req.method, req.url, '->', proxyReq.path);
          });
        },
      },
    },
  },

  // 微前端配置 - 开发和生产都使用相对路径
  base: './',

  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/element-variables.scss" as *;`,
      },
    },
  },

  plugins: [
    vue(),
    vueJsx(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      imports: ['vue', 'vue-router', 'pinia'],
      dts: 'src/auto-imports.d.ts',
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      dts: 'src/components.d.ts',
    }),
    qiankun('system-app', {
      useDevMode: true,
    }),
  ],

  // 优化依赖配置
  optimizeDeps: {
    include: [
      'vue',
      'vue-router',
      'pinia',
      'element-plus',
      '@element-plus/icons-vue',
      '@tuxing/network-http',
      '@tuxing/core-token',
      '@tuxing/utils-base',
    ],
  },

  build: {
    lib: {
      entry: './src/main.ts',
      name: 'systemApp',
      formats: ['umd'],
      fileName: 'systemApp',
    },
    rollupOptions: {
      external: ['vue', 'vue-router', 'pinia'],
      output: {
        globals: {
          vue: 'Vue',
          'vue-router': 'VueRouter',
          pinia: 'Pinia',
        },
      },
    },
  },
});

